<?php
class LogCommandHelper {

	public static function parseReferer($url){
		static $searchEngine  = array(
			'http://www.soso.com'=>'w',
			'http://www.google.com.hk'=>'q',
			'http://www.baidu.com'=>'wd',
			'http://search.yahoo.com'=>'p',
			'http://www.yahoo.cn'=>'q',
			'http://www.sogou.com'=>'query',
			'http://www.zhongsou.com'=>'w',
			'http://search.cn.yahoo.com'=>'p',
			'http://cn.bing.com'=>'q',

			'soso.com'=>'w',
			'google.com.hk'=>'q',
			'google.com'=>'q',
			'baidu.com'=>'wd',
			'yahoo.com'=>'p',
			'yahoo.cn'=>'q',
			'sogou.com'=>'query',
			'zhongsou.com'=>'w',
			'bing.com'=>'q',
			
		);
		
		$url = urldecode($url);
		$url = iconv('GBK', 'utf-8', $url);
		$result = array(
					
					'url'=>$url,
					'isEngine'=> false,
					'host'=>$url,	
					'keywords' =>array()
		);
		
		// get host name from URL
		@preg_match('@^(?:http://)?([^/]+)@i',$url, $matches);
		$host = $matches[1];
		
		
		@preg_match('/^[^.]+\.([^.]+\.[^.]+)/', $host, $matches);
		
		if(isset($matches[1]))
			$simpleHost = $matches[1];
		else{
			$simpleHost = $host;
		}
		
		$result['host'] = $host;
		
		if(in_array($simpleHost,array_keys($searchEngine))){
			$result['isEngine'] = true;
			
			$key = $searchEngine[$simpleHost];
			 
			
			@preg_match("/\W+$key\=([^&]+)/i", $url, $matches);
			if(isset($matches[1])){
				
				$keywords = trim($matches[1]);

//				print_r( mb_detect_encoding($keywords) );
				$keywords = mb_split ('/\W+/',$keywords);
				$keywords = array_filter($keywords);
				$result['keywords'] = $keywords;
				
//				echo strlen($keywords[0]);
			}
			
		}
	return $result;
	
	}
}

//$url= "www.google.com.hk/search?sourceid=chrome&ie=UTF-8&q=%C6%D5%CD%A8%C8%CB";
//print_r( LogCommandHelper::parseReferer($url));
?>
